package com.lfy.pay.zfb;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;

@Component
@EnableConfigurationProperties(ZfbOptions.class)
@ConditionalOnProperty(prefix = "pay.alipay", name = "enabled", havingValue = "true",matchIfMissing = false)
@Import(AlipayApi.class)
@Slf4j
public class ZfbConfig {
    @Resource
    private ZfbOptions zfbOptions;
    {
      log.info("alipayConfigApi  init ");
    }


    private AlipayConfig alipayConfig() throws FileNotFoundException {

        AlipayConfig alipayConfig = new AlipayConfig();
//设置网关地址
        alipayConfig.setServerUrl(zfbOptions.getGatewayHost());
//设置应用ID
        alipayConfig.setAppId(zfbOptions.getAppid());
//设置应用私钥
        alipayConfig.setPrivateKey(zfbOptions.getPrivateKey());
//设置请求格式，固定值json
        alipayConfig.setFormat(ZfbConstant.JSON);
//设置字符集
        alipayConfig.setCharset(ZfbConstant.CHARSET);
//设置签名类型
        alipayConfig.setSignType(zfbOptions.getSignType());
        //证书模式
    if(ZfbConstant.CERT.equals(zfbOptions.getType())){
            File file = ResourceUtils.getFile("/appPublicCert.crt");
        File pFile = ResourceUtils.getFile("/alipayPublicCert.crt");
        File rFile = ResourceUtils.getFile("/alipayRootCert.crt");
//设置应用公钥证书路径
        alipayConfig.setAppCertPath(file.getPath());
//设置支付宝公钥证书路径
        alipayConfig.setAlipayPublicCertPath(pFile.getPath());
//设置支付宝根证书路径
        alipayConfig.setRootCertPath(rFile.getPath());
        log.info("Zfb 证书模式");
    }else {
        alipayConfig.setAlipayPublicKey(zfbOptions.getPublicKey());
            log.info("Zfb 公钥模式");
    }
//设置连接池中的最大可缓存的空闲连接数
        alipayConfig.setMaxIdleConnections(5);
//连接超时，单位：毫秒，默认3000
        alipayConfig.setConnectTimeout(3000);
//读取超时，单位：毫秒，默认15000
        alipayConfig.setReadTimeout(15000);
//空闲连接存活时间，单位：毫秒，默认10000L
        alipayConfig.setKeepAliveDuration(10000L);

        return alipayConfig;
    }

    @Bean
    public AlipayClient alipayClient() throws AlipayApiException, FileNotFoundException {
        return new DefaultAlipayClient(alipayConfig());
    }

}
